﻿using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Metadata.Entity;
using T.FAS.Runtime.ScheduleJob.SPI;

namespace T.FAS.Runtime.ScheduleJob.Service
{
    public class ScheduleJobExecuteContextBuilder
    {
        public static ScheduleJobExecContext Build(ScheduleJobInstance instance)
        {
            if (instance == null)
                return null;
            var context = new ScheduleJobExecContext();
            context.Instance = instance;
            Metadata.Entity.ScheduleJob.ScheduleJob job = null;
            if (instance.ScheduleJobMetadata != null && instance.ScheduleJobMetadata.JobType == Metadata.Entity.ScheduleJob.JobType.Subscription)
            {
                job = instance.ScheduleJobMetadata;
            }
            else if (instance.ScheduleJobMetadata != null && instance.ScheduleJobMetadata.Ext1 == "userdefine")
            {
                job = instance.ScheduleJobMetadata;
            }
            else
            {
                IMetaDataContent metaData = null;
                metaData = MetadataRTPService.GetInstance().GetMetadata(instance.ScheduleJobID);
                job = metaData as Metadata.Entity.ScheduleJob.ScheduleJob;
            }
            context.ScheduleJobMetaData = job;
            context.ScheduleJobID = job.ID;
            //20230418 这里需要去掉判断，
            //因为存在通过计划任务的编号启动任务的场景，导致instance的ScheduleJobID存的是计划任务的Code，而store中用的是ScheduleJobID的ID；从而生成Jobkey不同，无法删除qrtz中的任务实例
            //这里需要强制更新instance的ScheduleJobID为元数据的ID
            //if (string.IsNullOrEmpty(instance.ScheduleJobID))
                instance.ScheduleJobID = job.ID;
            if (string.IsNullOrEmpty(instance.ScheduleJobGroup))
                instance.ScheduleJobGroup = job.ScheduleGroup;
            context.JobKey = ScheduleJobKeyUtil.GetJobKey(instance);
            context.TriggerKey = ScheduleJobKeyUtil.GetTriggerKey(instance);
            return context;
        }
    }
}
